let local = "http://localhost:25080"


//登入函数
function login(event){
	local = "http://localhost:25080"
	event.preventDefault(); 
	let loginName = $("input[name=name]").val()
	let password = $("input[name=password]").val()
	let rememberMe  = $("#brand1").is(":checked") 
	console.log("登入名："+loginName)
	console.log("密码："+password)
	local = local+"/employees/login"

	$.ajax({
		url:local,
		type:"POST",
		contentType: "application/x-www-form-urlencoded",
		data:{
			loginName: loginName,
			password: password,
		},
		success:function(response){
			
			if(response.data==null){
				alert("登入失败")
			}else{
				console.log("登入成功")
				if(rememberMe){
					console.log("保存到本地")
					setCookie("userData", JSON.stringify(response.data), 30); // 保存30天
				}else{
					console.log("不保存到本地")
				}
				
				console.log("跳转到主页面")
				window.location.href="/default.html"
			}
			
		},
		error:function(response){
			console.log("登入失败")
		}
	})
	
}

// 设置cookie的函数
function setCookie(name, value, days) {
    let expires = "";
    if (days) {
        let date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toUTCString();
    }
    document.cookie = name + "=" + (value || "") + expires + "; path=/";
}

// 获取cookie的函数
function getCookie(name) {
    let nameEQ = name + "=";
    let ca = document.cookie.split(';');
    for (let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

// 删除cookie的函数
function eraseCookie(name) {   
    document.cookie = name + '=; Max-Age=-99999999; path=/'; 
}

//比较两个密码是否为一个密码
function compare(event){
	
	event.preventDefault(); 
	let password = $("input[name=Password]").val()
	let password1 =$("input[name=Password1]").val()
	if(password==password1){
		add()
	}else{
		alert("两次密码不同")
		return false;
	}
}

//注册用户
function add(){	
	local = "http://localhost:25080"
	let data={
		loginName: $("input[name=Name]").val(),
		email:$("input[name=Email]").val(),
		password:$("input[name=Password]").val()
	}
	local+="/employees/add"
	$.ajax({
		url:local,
		type:"POST",
		contentType: "application/json",
		data: JSON.stringify(data),  
		success:function(response){
			if(!response.status){
				alert("用户名已存在！")
				console.log(response)
			}else{
				console.log(response)
				alert("注册成功")
			}
				
		},
		error:function(response){
			console.log(response)
		}
	})
	
}